package ro.fortech.workshop_demo.activities;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.*;
import ro.fortech.workshop_demo.R;
import ro.fortech.workshop_demo.business.BusinessConstants;
import ro.fortech.workshop_demo.business.SeasonsManager;
import ro.fortech.workshop_demo.ui.GrandPrixListAdapter;
import ro.fortech.workshop_demo.ui.GrandPrixListDelegate;
import ro.fortech.workshop_demo.utils.Utils;

import java.util.Calendar;

/**
 * User: florinv
 * Date: 4/16/13
 * Time: 10:55 AM
 */
public class Seasons extends Main implements AdapterView.OnItemSelectedListener, GrandPrixListDelegate {
    /**
     * Spinner holding all seasons starting from 1950 to today
     */
    private Spinner seasonsPicker;
    /**
     * Array adapter providing the views displayed into the spinner
     */
    private ArrayAdapter<String> seasonsPickerAdapter;
    /**
     * ListView holding the races from the selected season
     */
    private ListView grandPrixListView;
    /**
     * Array adapter providing the views displayed into the list
     */
    private GrandPrixListAdapter grandPrixListAdapter;
    /**
     * Intent filter for the grand prix list successfully parsed business intent
     */
    private IntentFilter grandPrixListParseSuccessFilter;
    /**
     * Intent filter for the grand prix list parse error business intent
     */
    private IntentFilter grandPrixListParseErrorFilter;
    /**
     * Name of the key for the clicked row index intent extra
     */
    public static final String EXTRA_ROW_INDEX = "RowIndex";

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // This activity will get a custom title. Must be called before setting the content of the activity
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.seasons);
        // Set the custom title layout
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
        // Set the custom title
        TextView customTitle = (TextView) findViewById(R.id.custom_title_text);
        customTitle.setText("Formula 1");
        // Inflate the seasons picker
        seasonsPicker = (Spinner) findViewById(R.id.season_picker);
        // Create the seasons picker adapter
        seasonsPickerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        seasonsPickerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Populate the spinner with all seasons starting from 1950
        for (int i = 1950; i <= Calendar.getInstance().get(Calendar.YEAR); i++) {
            seasonsPickerAdapter.add(String.format(getString(R.string.seasons_picker_text), Integer.toString(i)));
        }
        seasonsPicker.setAdapter(seasonsPickerAdapter);
        // Set a click listener to intercept clicks on items populating the picker
        seasonsPicker.setOnItemSelectedListener(this);
        // Set the default selected item to season 2000
        seasonsPicker.setSelection(50);
        // Inflate the list holding the races for the current season
        grandPrixListView = (ListView) findViewById(R.id.season_race_list);
    }

    @Override
    public void onResume() {
        super.onResume();
        // Register the activity receivers
        registerBroadcastReceivers();
    }

    @Override
    public void onPause() {
        super.onPause();
        // Unregister the activity receivers
        unregisterBroadcastReceivers();
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        getGrandPrixList();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // Method implemented just because forced by interface
    }

    @Override
    public void rowClicked(int position) {
        Bundle bundle = new Bundle();
        bundle.putInt(EXTRA_ROW_INDEX, position);
        Utils.navigate(Seasons.this, GrandPrixDetails.class, false, bundle, R.anim.slide_in_right, R.anim.slide_out_left);
    }

    /**
     * Method used for calling the business manager method for retrieving the grand prix list
     */
    private void getGrandPrixList() {
        // Show the progress dialog to notify the user the the call to the web service has been made
        Utils.showProgressDialog(this);
        // Call the method from the business manager
        SeasonsManager.getInstance().getGrandPrixList(seasonsPicker.getSelectedItem().toString().replace("Season", "").trim());
    }

    /**
     * Register the activity broadcast receivers
     */
    private void registerBroadcastReceivers() {
        // Instantiate the receivers
        if (successBroadcastReceiver == null) {
            successBroadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    // Handle the get grand prix list success response
                    if (intent.getAction().equals(BusinessConstants.NTF_SM_GRAND_PRIX_LIST_PARSE_SUCCESS)) {
                        Utils.hideProgressDialog(Seasons.this);
                        if (grandPrixListAdapter == null) {
                            // Create the view for header/footer
                            View view = new View(Seasons.this);
                            view.setBackgroundResource(R.drawable.list_divider);
                            // Set the header
                            grandPrixListView.addHeaderView(view);
                            // Set the footer
                            grandPrixListView.addFooterView(view);
                            // Create the adapter for the list
                            grandPrixListAdapter = new GrandPrixListAdapter(Seasons.this, R.layout.grand_prix_list_row,
                                    SeasonsManager.getInstance().getGrandPrixList(), Seasons.this);
                            // Set the adapter to the list
                            grandPrixListView.setAdapter(grandPrixListAdapter);
                            // Set the OnScrollListener to the list
                            grandPrixListView.setOnScrollListener(grandPrixListAdapter);
                        } else {
                            grandPrixListAdapter.notifyDataSetChanged();
                        }
                    }
                }
            };
        }

        if (errorBroadcastReceiver == null) {
            errorBroadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    // Handle the get grand prix list error response
                    if (intent.getAction().equals(BusinessConstants.NTF_SM_GRAND_PRIX_LIST_PARSE_ERROR)) {
                        Utils.hideProgressDialog(Seasons.this);
                        AlertDialog.Builder builder = new AlertDialog.Builder(Seasons.this);
                        builder.setCancelable(false);
                        builder.setTitle(R.string.error);
                        builder.setMessage(R.string.grand_prix_list_parse_error_message);
                        builder.setPositiveButton(R.string.ok, null);
                        builder.create().show();
                    }
                }
            };
        }

        // Instantiate the filters
        if (grandPrixListParseSuccessFilter == null) {
            grandPrixListParseSuccessFilter = new IntentFilter(BusinessConstants.NTF_SM_GRAND_PRIX_LIST_PARSE_SUCCESS);
        }
        if (grandPrixListParseErrorFilter == null) {
            grandPrixListParseErrorFilter = new IntentFilter(BusinessConstants.NTF_SM_GRAND_PRIX_LIST_PARSE_ERROR);
        }

        // Register the register the receivers
        registerReceiver(successBroadcastReceiver, grandPrixListParseSuccessFilter);
        registerReceiver(errorBroadcastReceiver, grandPrixListParseErrorFilter);
    }

    /**
     * Method used for unregistering the activity broadcast receivers
     */
    private void unregisterBroadcastReceivers() {
        unregisterReceiver(successBroadcastReceiver);
        unregisterReceiver(errorBroadcastReceiver);
    }
}
